<?php

namespace plugin\admin\app\controller;

use plugin\admin\app\common\Util;
use plugin\admin\app\model\Option;
use plugin\admin\app\model\User;
use plugin\csauto\app\model\RssModel;
use plugin\csauto\app\model\TorrentTaskModel;
use plugin\csauto\app\model\TorrentReleaseModel;
use plugin\csauto\app\model\TorrentListModel;
use plugin\csauto\app\model\SiteModel;
use support\exception\BusinessException;
use support\Request;
use support\Response;
use think\db\Where;
use Throwable;
use Workerman\Worker;

class IndexController
{

    /**
     * 无需登录的方法
     *
     * @var string[]
     */
    protected $noNeedLogin = ['index'];

    /**
     * 不需要鉴权的方法
     *
     * @var string[]
     */
    protected $noNeedAuth = ['dashboard'];

    /**
     * 后台主页
     *
     * @param Request $request
     * @return Response
     * @throws BusinessException|Throwable
     */
    public function index(Request $request): Response
    {
        if (getenv('WORK_DEBUG')) {
            return response('Node does not provide webui');
        }
        clearstatcache();
        if (!is_file(base_path('plugin/admin/config/database.php'))) {
            return raw_view('index/install');
        }
        $admin = admin();
        if (!$admin) {
            $name = 'system_config';
            $config = Option::where('name', $name)->value('value');
            $config = json_decode($config, true);
            $title = $config['logo']['title'] ?? 'webman admin';
            $logo = $config['logo']['image'] ?? '/app/admin/admin/images/logo.png';
            return raw_view('account/login', ['logo' => $logo, 'title' => $title]);
        }
        return raw_view('index/index');
    }

    /**
     * 仪表板
     *
     * @param Request $request
     * @return Response
     * @throws Throwable
     */
    public function dashboard(Request $request): Response
    {
        // CSAuto相关统计数据
        // RSS种子数量 - 获取实际采集到的种子数量
        $rss_count = \plugin\csauto\app\model\TorrentListModel::count();

        // 下载任务数量
        $download_task_count = TorrentTaskModel::count();

        // 种子发布数量 - 总数和成功数
        $torrent_release_total = TorrentReleaseModel::count();
        $torrent_release_success = TorrentReleaseModel::where('task_status', 1)->count();

        // 允许源站的站点数量（get_status为1的站点）
        $source_site_count = SiteModel::where('get_status', 1)->count();

        // 允许发布站的站点数量（out_status为1的站点）
        $publish_site_count = SiteModel::where('out_status', 1)->count();

        // 获取15日种子发布统计数据（按状态分组）
        $day15_detail = [];
        $now = time();
        for ($i = 0; $i < 15; $i++) {
            $date = date('Y-m-d', $now - 24 * 60 * 60 * $i);
            $date_str = substr($date, 5);

            // 获取该日期各种状态的发布任务数量
            $status_counts = TorrentReleaseModel::selectRaw('task_status, COUNT(*) as count')
                ->where('created_at', '>', "$date 00:00:00")
                ->where('created_at', '<', "$date 23:59:59")
                ->groupBy('task_status')
                ->pluck('count', 'task_status');

            $day15_detail[$date_str] = [
                'total' => array_sum($status_counts->values()->toArray()),
                'pending' => $status_counts->get(0, 0),      // 待发布
                'success' => $status_counts->get(1, 0),      // 发布成功
                'duplicate' => $status_counts->get(2, 0),    // 资源重复
                'failed' => $status_counts->get(3, 0),       // 发布失败
                'task_not_exists' => $status_counts->get(4, 0), // 任务不存在
                'task_ended' => $status_counts->get(5, 0),   // 任务已结束
                'torrent_not_exists' => $status_counts->get(6, 0), // 源站种子不存在
                'completed' => $status_counts->get(99, 0),   // 完结
            ];
        }

        // 获取Git版本信息
        $git_info = $this->getGitVersionInfo();

        // mysql版本
        $version = Util::db()->select('select VERSION() as version');
        $mysql_version = $version[0]->version ?? 'unknown';

        return raw_view('index/dashboard', [
            // CSAuto统计数据
            'rss_count' => $rss_count,
            'download_task_count' => $download_task_count,
            'torrent_release_total' => $torrent_release_total,
            'torrent_release_success' => $torrent_release_success,
            'source_site_count' => $source_site_count,
            'publish_site_count' => $publish_site_count,
            'day15_detail' => array_reverse($day15_detail),
            'git_current_version' => $git_info['current_version'] ?? 'unknown',
            'git_has_update' => $git_info['has_update'] ?? false,
            'git_latest_version' => $git_info['latest_version'] ?? '',

            // 原有系统信息
            'php_version' => PHP_VERSION,
            'workerman_version' => Worker::VERSION,
            'webman_version' => Util::getPackageVersion('workerman/webman-framework'),
            'admin_version' => Util::getPackageVersion('webman/admin'),
            'mysql_version' => $mysql_version,
            'os' => PHP_OS,
        ]);
    }

    /**
     * 系统升级
     *
     * @param Request $request
     * @return Response
     */
    public function upgrade(Request $request): Response
    {
        try {
            $rootPath = base_path();
            chdir($rootPath);

            // 检查是否为git仓库
            $checkGit = shell_exec('git rev-parse --is-inside-work-tree 2>&1');
            if (trim($checkGit) !== 'true') {
                return json(['code' => 1, 'msg' => '当前目录不是有效的 git 仓库']);
            }

            // 获取当前分支
            $currentBranch = trim(shell_exec('git rev-parse --abbrev-ref HEAD'));

            // 获取远程仓库URL并验证是否为目标仓库
            $remoteUrl = trim(shell_exec('git remote get-url origin'));
            if ($remoteUrl !== 'https://gitee.com/lumingjie/cs-auto-core.git') {
                return json(['code' => 1, 'msg' => '远程仓库地址不匹配，无法升级']);
            }

            // 获取本地最新 commit hash
            $localHash = trim(shell_exec('git rev-parse HEAD'));

            // 获取远程最新 commit hash
            shell_exec('git fetch origin');
            $remoteHash = trim(shell_exec("git rev-parse origin/{$currentBranch}"));

            // 比较本地和远程版本
            if ($localHash === $remoteHash) {
                return json(['code' => 1, 'msg' => '当前已是最新版本，无需升级']);
            }

            // 执行 git pull 更新代码
            $output = [];
            $returnCode = 0;
            exec('git pull origin ' . $currentBranch . ' 2>&1', $output, $returnCode);

            if ($returnCode === 0) {
                // 更新成功，执行composer install更新依赖（如果需要）
                if (is_file(base_path('composer.json'))) {
                    shell_exec('composer install --no-dev --optimize-autoloader 2>&1');
                }

                return json(['code' => 0, 'msg' => '升级成功']);
            } else {
                return json(['code' => 1, 'msg' => '升级失败：' . implode("\n", $output)]);
            }
        } catch (\Exception $e) {
            return json(['code' => 1, 'msg' => '升级过程中发生错误：' . $e->getMessage()]);
        }
    }

    /**
     * 获取Git版本信息
     *
     * @return array
     */
    private function getGitVersionInfo(): array
    {
        try {
            $rootPath = base_path();
            chdir($rootPath);

            // 检查是否为git仓库
            $checkGit = shell_exec('git rev-parse --is-inside-work-tree 2>&1');
            if (trim($checkGit) !== 'true') {
                return ['current_version' => 'not_git_repo'];
            }

            // 获取当前commit hash（短格式）
            $currentHash = trim(shell_exec('git rev-parse --short HEAD'));

            // 获取远程仓库信息
            $remoteUrl = trim(shell_exec('git remote get-url origin 2>&1'));

            // 检查是否有更新
            shell_exec('git fetch origin 2>&1');
            $currentBranch = trim(shell_exec('git rev-parse --abbrev-ref HEAD'));
            $remoteHash = trim(shell_exec("git rev-parse origin/{$currentBranch} 2>&1"));

            $hasUpdate = $currentHash !== $remoteHash && !empty($remoteHash);

            return [
                'current_version' => $currentHash,
                'has_update' => $hasUpdate,
                'latest_version' => $hasUpdate ? $remoteHash : $currentHash,
                'remote_url' => $remoteUrl,
            ];
        } catch (\Exception $e) {
            return ['current_version' => 'error', 'error' => $e->getMessage()];
        }
    }

}
